// bitmap.h

// Copyright (C) 2010  traxex

// Author: 	traxex <traxex@yahoo.cn>
// Created: 	11 Aug 2010
// Version: 	1.0

#pragma once

#include <traxex/cuda.h>
#include <GL/glut.h>

namespace Traxex{
namespace Cuda{

struct __align__(4) Point{
    uint8_t r;
    uint8_t g;
    uint8_t b;
    uint8_t a;
};

namespace{
    int		bitmap_x;
    int		bitmap_y;
    void*	bitmap_p;
}

template<size_t X, size_t Y>class BitMap{
    typedef Point Data[X];
  public:
    BitMap(){
        static bool init = class_init();
        hdata = hmalloc<Data>(Y);
        ddata = dmalloc<Data>(Y);
    }

    ~BitMap(){
        hfree( hdata);
        dfree( ddata);
    }

    void show( const char* title=""){
        d2hcpy( hdata, ddata, Y);
        bitmap_x	= X;
        bitmap_y	= Y;
        bitmap_p	= hdata;

        glutInitWindowSize( X, Y );
        glutCreateWindow( title);
        glutDisplayFunc(  BitMap::draw_callback );
        glutMainLoop();
    }

    operator Data* (){ return ddata;}

  private:
    Data	*hdata;
    Data	*ddata;
    BitMap( const BitMap&);
    BitMap& operator=( const BitMap&);

    static void draw_callback(){
        glClearColor( 0, 0, 0, 1);
        glClear( GL_COLOR_BUFFER_BIT );
        glDrawPixels( bitmap_x, bitmap_y, GL_RGBA, GL_UNSIGNED_BYTE, bitmap_p );
        glFlush();
    }
    static bool class_init(){
        int   argc=0;
        char* argv[]={""};
        glutInit( &argc, argv);
        glutInitDisplayMode( GLUT_SINGLE | GLUT_RGBA );
        return true;
    }
};
}
}
